package module.common.net;

import java.io.IOException;

import library.net.RxRetrofitUtils;
import library.net.retrofit.interceptor.RxTokenInterceptor;
import module.common.net.data.BeanForRefreshToken;
import module.common.share.SharedManager;
import retrofit2.Call;

/**
 * @author Created by qiang.hou on 2018/12/11.
 * @version 1.0
 */
public class TokenInterceptor extends RxTokenInterceptor {
    @Override
    protected String getToken() {
        String tokenValue = "";
        if (isExpires()) {
            Call<BeanForRefreshToken> tokenCall = RxRetrofitUtils.getInstance()
                    .create(ICommonService.class)
                    .refreshToken("refresh_token",
                            SharedManager.getInstance().getValue(SharedManager.KEY_REFRESH_TOKEN_VALUE, ""));
            BeanForRefreshToken data = null;
            try {
                data = tokenCall.execute().body();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (data != null) {
                    SharedManager.getInstance().refreshToken(data);
                    tokenValue = data.tokenType + " " + data.value;
                } else {
                    //获取不到token直接清除登录信息
                    SharedManager.getInstance().clearUserData();
//                    .getInstance().showReLoginDialogByHandler();
                }
            }
        } else {
            tokenValue = SharedManager.getInstance().getValue(SharedManager.KEY_TOKEN_TYPE, "")
                    + " "
                    + SharedManager.getInstance().getValue(SharedManager.KEY_TOKEN_VALUE, "");
        }

        return tokenValue;
    }

    private boolean isExpires() {
        long expiresTime = SharedManager.getInstance().getValue(SharedManager.KEY_TOKEN_EXPIRES_TIME, 0L);

        return System.currentTimeMillis() > expiresTime;
    }
}
